package flc.ast.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import android.os.Handler;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.DrawActivity;
import flc.ast.adapter.AddDrawAdapter;
import flc.ast.adapter.RecordAdapter;
import flc.ast.adapter.TemplateAdapter;
import flc.ast.bean.MyTemplateBean;
import flc.ast.databinding.FragmentDrawBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DrawFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DrawFragment extends BaseNoModelFragment<FragmentDrawBinding> {

    private TemplateAdapter templateAdapter;
    private Dialog myAddDrawDialog;
    private AddDrawAdapter addDrawAdapter;
    private int selPosition;
    private RecordAdapter recordAdapter;
    private List<String> listShow = new ArrayList<>();
    private String selPath = "";
    private Dialog myClearDialog;


    @Override
    protected int onCreate() {
        return R.layout.fragment_draw;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.tvTemplate.setOnClickListener(this);
        mDataBinding.tvMyWork.setOnClickListener(this);

        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        mDataBinding.rvTemplateList.setLayoutManager(layoutManager);
        templateAdapter = new TemplateAdapter();
        mDataBinding.rvTemplateList.setAdapter(templateAdapter);
        templateAdapter.addChildClickViewIds(R.id.ivTemplateItemUse);
        templateAdapter.setOnItemChildClickListener(this);

        mDataBinding.rvMyWorkList.setLayoutManager(new GridLayoutManager(mContext, 3));
        recordAdapter = new RecordAdapter();
        mDataBinding.rvMyWorkList.setAdapter(recordAdapter);
        recordAdapter.addChildClickViewIds(R.id.ivRecordItemDelete);
        recordAdapter.setOnItemChildClickListener(this);

        mDataBinding.ivAddDraw.setOnClickListener(this);

        //新建画板弹框
        addDrawDialog();
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAddDraw://新建画板
                myAddDrawDialog.show();
                break;
            case R.id.tvTemplate://模板
                clearSelection();
                mDataBinding.tvTemplate.setTextColor(Color.parseColor("#161515"));
                mDataBinding.rvTemplateList.setVisibility(View.VISIBLE);
                break;
            case R.id.tvMyWork://我的作品
                clearSelection();
                mDataBinding.tvMyWork.setTextColor(Color.parseColor("#161515"));
                mDataBinding.rvMyWorkList.setVisibility(View.VISIBLE);
                break;
            //新建画板弹框
            case R.id.ivDialogAddDrawCancel:
                myAddDrawDialog.dismiss();
                break;
            case R.id.tvDialogAddDrawConfirm:
                gotoDraw(selPosition + 1);
                myAddDrawDialog.dismiss();
                break;
            //删除弹框
            case R.id.tvDialogClearCancel://取消
                myClearDialog.dismiss();
                break;
            case R.id.tvDialogClearRight://确定
                myClearDialog.dismiss();
                deletePicture();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        selPosition = position;
        addDrawAdapter.setPosition(position);
        addDrawAdapter.notifyDataSetChanged();
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()) {
            case R.id.ivTemplateItemUse:
                gotoTempDraw(templateAdapter.getItem(position).getImg());
                break;
            case R.id.ivRecordItemDelete:
                selPath = recordAdapter.getItem(position);
                myClearDialog.show();
                break;
        }
    }

    @Override
    protected void initData() {
        List<MyTemplateBean> listTemp = new ArrayList<>();
        listTemp.add(new MyTemplateBean(getString(R.string.template_name1), R.drawable.mb1, R.drawable.mb1a));
        listTemp.add(new MyTemplateBean(getString(R.string.template_name2), R.drawable.mb2, R.drawable.mb2a));
        listTemp.add(new MyTemplateBean(getString(R.string.template_name1), R.drawable.mb3, R.drawable.mb3a));
        listTemp.add(new MyTemplateBean(getString(R.string.template_name1), R.drawable.mb4, R.drawable.mb4a));
        listTemp.add(new MyTemplateBean(getString(R.string.template_name1), R.drawable.mb5, R.drawable.mb5a));
        templateAdapter.setList(listTemp);
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        listShow.clear();
        //获取文件夹下文件
        String path = PathUtils.getFilesPathExternalFirst() + Content.myDraw;
        List<File> files = FileUtils.listFilesInDir(path);
        if (files.size() > 0) {
            for (File file : files) {
                listShow.add(file.getPath());
            }
        }
        recordAdapter.setList(listShow);
    }

    //去到绘画界面
    private void gotoTempDraw(int img) {
        DrawActivity.kind = 1;
        DrawActivity.selImg = img;
        startActivity(DrawActivity.class);
    }

    //去到绘画界面
    private void gotoDraw(int bili) {
        DrawActivity.kind = 2;
        DrawActivity.bili = bili;
        startActivity(DrawActivity.class);
    }

    //删除图片
    private void deletePicture() {
        showDialog(getString(R.string.delete_ing));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        FileUtils.delete(selPath);
                        emitter.onNext("");
                    }

                    @Override
                    public void accept(String bitmap) {
                        dismissDialog();
                        getData();
                    }
                });
            }
        }, 500);
    }


    //新建画板弹框
    private void addDrawDialog() {
        myAddDrawDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_draw, null);
        myAddDrawDialog.setContentView(inflate);
        myAddDrawDialog.setCancelable(false);
        Window dialogWindow = myAddDrawDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogAddDrawCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogAddDrawConfirm);
        RecyclerView recyclerView = inflate.findViewById(R.id.rvAddDrawList);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        addDrawAdapter = new AddDrawAdapter();
        recyclerView.setAdapter(addDrawAdapter);
        addDrawAdapter.setOnItemClickListener(this);
        List<String> list = Arrays.asList(getResources().getStringArray(R.array.add_draw));
        addDrawAdapter.setList(list);
        addDrawAdapter.setPosition(selPosition);

        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
    }

    //删除弹框
    private void deleteDialog() {
        myClearDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_clear, null);
        myClearDialog.setContentView(inflate);
        myClearDialog.setCancelable(false);
        Window dialogWindow = myClearDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.6);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView dialogCancel = inflate.findViewById(R.id.tvDialogClearCancel);
        TextView dialogRight = inflate.findViewById(R.id.tvDialogClearRight);
        TextView dialogTitle = inflate.findViewById(R.id.tvDialogClearTitle);
        TextView dialogText = inflate.findViewById(R.id.tvDialogClearText);
        dialogTitle.setText(R.string.delete_draw);
        dialogText.setText(R.string.delete_draw_text);
        dialogCancel.setOnClickListener(this);
        dialogRight.setOnClickListener(this);
    }

    private void clearSelection() {
        mDataBinding.tvTemplate.setTextColor(Color.parseColor("#B1B1B1"));
        mDataBinding.tvMyWork.setTextColor(Color.parseColor("#B1B1B1"));
        mDataBinding.rvTemplateList.setVisibility(View.GONE);
        mDataBinding.rvMyWorkList.setVisibility(View.GONE);
    }

}